Welcome to JavaScript!

4.4 switch条件语句

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<script type="text/javascript">

var a=prompt("请输入日期:")*1; //输入的是字符窜,*1则是把字符窜转成数字类型

switch (a) { //括号中是判断的对象

case 8: //case是要判断对象的值

document.write("食品8折");

case 18:

document.write("服装8折");

case 28:

document.write("电器8折");

}

</script>

</head>

<body>

</body>

</html>

以上代码输入8,则会返回:

食品8折服装8折电器8折

这是因为语句满足后不会停止退回,会继续运行代码,需加入brank语句中止。


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<script type="text/javascript">

var a=prompt("请输入日期:")*1; //输入的是字符窜,*1则是把字符窜转成数字类型

switch (a) { //括号中是判断的对象

case 8: //case是要判断对象的值

document.write("食品8折");

break;

case 18:

document.write("服装8折");

break;

case 28:

document.write("电器8折");

break;

default: //当所有条件不成立时,返回错误信息

document.write("不打折");

break;

}

</script>

</head>

<body>

</body>

</html>